//
//  DFTextView.m
//  DFTextField
//
//  Created by 如佳 陈 on 15/8/17.
//  Copyright (c) 2015年 crj. All rights reserved.
//

#import "DFTextView.h"

@interface DFTextView(){
    
}

@property (nonatomic, strong) UILabel *placeHolderLabel;

@end

@implementation DFTextView

- (instancetype)init{
    if (self = [super init]) {
        [self initialize];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]) {
        [self initialize];
    }
    return self;
}

- (void)initialize{
    [self addSubview:self.placeHolderLabel];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange:) name:UITextViewTextDidChangeNotification object:nil];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setPlaceholder:(NSString *)placeholder{
    _placeholder = placeholder;
    self.placeHolderLabel.text = _placeholder;
    CGRect bounds = [_placeholder boundingRectWithSize:CGSizeMake(self.frame.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.font} context:nil];
    self.placeHolderLabel.frame = CGRectMake(4, 8, bounds.size.width, bounds.size.height);
}

- (void)setBorderColor:(UIColor *)borderColor{
    self.layer.borderColor = [borderColor CGColor];
}

- (void)setBorderWidth:(CGFloat)borderWidth{
    self.layer.borderWidth = borderWidth;
}

- (void)setCornerRadius:(CGFloat)cornerRadius{
    self.clipsToBounds = cornerRadius > 0;
    self.layer.cornerRadius = cornerRadius;
}

- (UILabel *)placeHolderLabel{
    if (_placeHolderLabel == nil) {
        _placeHolderLabel = [[UILabel alloc]init];
        _placeHolderLabel.font = self.font;
        _placeHolderLabel.textColor = [UIColor lightGrayColor];
    }
    return _placeHolderLabel;
}

- (void)textChange:(NSNotification*)not{
    if(((UITextView*)not.object).text.length == 0){
        self.placeHolderLabel.hidden = NO;
    }else{
        self.placeHolderLabel.hidden = YES;
    }
}

@end
